# coding:utf-8
import requests
from flask import Flask, render_template, redirect, request, session, g  # 引入request对象
import tensorflow as tf
import pickle
import random
import numpy as np
import warnings
import json
from urllib import parse
import os

os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
warnings.filterwarnings('ignore')

app = Flask(__name__)

@app.route("/getRec/<movieId>", methods=["GET", "POST"])
def getRec(movieId):
    # # requset.form获取表单格式的请求参数(name=zhangsan&age=18) (类似字典的对象)
    # age = request.form.get("age", "默认值")
    # # get方法只能拿到多个同名参数的第一个，getlist可以获取所有。
    # name_li = request.form.getlist("name")  # 获取同名参数的所有值,返回列表
    # print("进入qingqiu")
    # 如果请求体的数据不是表单格式的（如json格式，xml格式），可以通过request.data获取
    # print(request.data)  # {"name": "zhangsan", "age": 18} (Json字符串)。request.get_json() 直接返回字典,而不是Json字符串(需要前端设置请求头)。
    # print("传递数据："+movieId)
    recom = recommend_other_favorite_movie(int(movieId),15,6)
    # request.args.add("recommend",recom)
    # print(recom)
    data=""
    for r in recom:
        data=data+str(r)+","
    # print(data[:-1])
    # return redirect("http://localhost:8080/detail/movieId="+str(movieId))
    return redirect("http://localhost:8080/detail/movieId="+str(movieId)+"/recom="+data[:-1])
    # requests.post("http://localhost:8080/detail/movieId="+str(movieId),data=recom)

def recommend_other_favorite_movie(movie_id_val, top_k = 20, num=6):
    load_dir='E:\\WorkspaceForJava\\movie-recommender\\src\\main\\resources\\static\\py\\model\\save'
    movie_matrics = pickle.load(open('E:\\WorkspaceForJava\\movie-recommender\\src\\main\\resources\\static\\py\\data\\movie_matrics.p', mode='rb'))
    title_count, title_set, genres2int, features, targets_values, ratings, users, movies, data, movies_orig, users_orig = \
        pickle.load(open('E:\\WorkspaceForJava\\movie-recommender\\src\\main\\resources\\static\\py\\data\\preprocess.p', mode='rb'))
    movieid2idx = {val[0]:i for i, val in enumerate(movies.values)}
    users_matrics = pickle.load(open('E:\\WorkspaceForJava\\movie-recommender\\src\\main\\resources\\static\\py\\data\\users_matrics.p', mode='rb'))

    loaded_graph = tf.Graph()  #
    with tf.Session(graph=loaded_graph) as sess:  #
        # Load saved model
        loader = tf.train.import_meta_graph('E:\\WorkspaceForJava\\movie-recommender\\src\\main\\resources\\static\\py\\model\\save.meta')
        loader.restore(sess, load_dir)

        probs_movie_embeddings = (movie_matrics[movieid2idx[movie_id_val]]).reshape([1, 200])
        probs_user_favorite_similarity = tf.matmul(probs_movie_embeddings, tf.transpose(users_matrics))
        favorite_user_id = np.argsort(probs_user_favorite_similarity.eval())[0][-top_k:]
        #     print(normalized_users_matrics.eval().shape)
        #     print(probs_user_favorite_similarity.eval()[0][favorite_user_id])
        #     print(favorite_user_id.shape)

        # print("您看的电影是：{}".format(movies_orig[movieid2idx[movie_id_val]]))

        # print("喜欢看这个电影的人是：{}".format(users_orig[favorite_user_id-1]))
        probs_users_embeddings = (users_matrics[favorite_user_id-1]).reshape([-1, 200])
        probs_similarity = tf.matmul(probs_users_embeddings, tf.transpose(movie_matrics))
        sim = (probs_similarity.eval())
        #     results = (-sim[0]).argsort()[0:top_k]
        #     print(results)

        #     print(sim.shape)
        #     print(np.argmax(sim, 1))
        p = np.argmax(sim, 1)
        # print("喜欢看这个电影的人还喜欢看：")

        results = set()
        while len(results) != num:
            c = p[random.randrange(top_k)]
            results.add(c)
        # for val in (results):
        #     print(val)
        #     print(movies_orig[val])
        #
        return results

if __name__ == '__main__':
    app.run(host="localhost", port=8081, debug=True)